package com.zuipin.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zuipin.entity.BalanceRecord;
import com.zuipin.entity.DrawLevelGroup;
import com.zuipin.entity.IntegralRecord;
import com.zuipin.entity.LoginRuleNum;
import com.zuipin.entity.MemberLevel;
import com.zuipin.entity.Prize;
import com.zuipin.entity.RedPacket;
import com.zuipin.entity.SysUser;
import com.zuipin.entity.product.ProductInfo;
import com.zuipin.entity.shoppingCart.ProRuleSet;
import com.zuipin.entity.shoppingCart.ProTypeLimit;
import com.zuipin.entity.shoppingCart.RuleSet;
import com.zuipin.entity.shoppingCart.RuleType;
import com.zuipin.entity.shoppingCart.ShoppingCart;
import com.zuipin.entity.shoppingCart.ShowType;
import com.zuipin.entity.shoppingCart.Status;
import com.zuipin.enums.BalanceType;
import com.zuipin.enums.IntegralType;
import com.zuipin.enums.PrizeType;
import com.zuipin.enums.RedPackStatus;
import com.zuipin.enums.RedPackType;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.PageResult;
import com.zuipin.framework.result.Result;
import com.zuipin.mapper.DrawLevelGroupMapper;
import com.zuipin.mapper.PrizeMapper;
import com.zuipin.mapper.ProRuleSetMapper;
import com.zuipin.mapper.RuleSetMapper;
import com.zuipin.mapper.RuleSetUseLogMapper;
import com.zuipin.service.IBalanceRecordService;
import com.zuipin.service.IDrawNumService;
import com.zuipin.service.IIntegralRecordService;
import com.zuipin.service.ILoginRuleNumService;
import com.zuipin.service.IMemberLevelService;
import com.zuipin.service.IMemberService;
import com.zuipin.service.IOrderService;
import com.zuipin.service.IProductInfoService;
import com.zuipin.service.IRedPacketService;
import com.zuipin.service.IRuleSetService;
import com.zuipin.service.IShoppingCartService;
import com.zuipin.service.ISysUserService;
import com.zuipin.util.ArithUtil;
import com.zuipin.util.CommonUtils;
import com.zuipin.util.ConstantsUtil;
import com.zuipin.util.DateUtils;
import com.zuipin.util.RedisUtils;
import com.zuipin.util.StringUtil;
import com.zuipin.util.ThreadPoolUtils;
import com.zuipin.vo.AddCartRuleVo;
import com.zuipin.vo.AddDrawRuleVo;
import com.zuipin.vo.AddRedPacketRuleVo;
import com.zuipin.vo.AddSpecialRuleVo;
import com.zuipin.vo.AddUserBehaviorRuleVo;
import com.zuipin.vo.CheckRuleSetParam;
import com.zuipin.vo.CheckRuleSetResult;
import com.zuipin.vo.DrawLevelGroupVo;
import com.zuipin.vo.ProVo;
import com.zuipin.vo.RuleListResponseVo;
import com.zuipin.vo.RuleResponseVo;
import com.zuipin.vo.SpecialPriceVo;

import net.sf.json.JSONObject;

@Service
@Transactional(rollbackFor = Exception.class)
public class RuleSetServiceImpl implements IRuleSetService {
	@Resource
	private RuleSetMapper			ruleSetMapper;
	
	@Resource
	private ProRuleSetMapper		proRuleSetMapper;
	
	@Resource
	private IMemberService			memberService;
	
	@Resource
	private DrawLevelGroupMapper	drawLevelGroupMapper;
	
	@Resource
	private PrizeMapper				prizeMapper;
	
	@Resource
	private IRedPacketService		redPacketService;
	
	@Resource
	private IMemberLevelService		memberLevelService;
	
	@Resource
	private IOrderService			orderService;
	
	@Resource
	private RuleSetUseLogMapper		ruleSetUseLogMapper;
	
	@Resource
	private IIntegralRecordService	integralRecordService;
	
	@Resource
	private IDrawNumService			drawNumService;
	
	@Resource
	private IBalanceRecordService	balanceRecordService;
	
	@Resource
	private ILoginRuleNumService	loginRuleNumService;
	
	@Resource
	private IProductInfoService		productInfoService;
	@Resource
	private IShoppingCartService	shoppingCartService;
	
	@Resource
	private ISysUserService			sysUserService;
	@Resource
	private RedisUtils				redisUtils;
	
	private final Logger			log			= LoggerFactory.getLogger(getClass());
	public static final int			INSERT_RED	= 10000;								// 批量插入红包
	public static final String		CREATE_RED	= "CREATE_RED";							// 创建红包标识
	
	/**
	 * 新增红包规则
	 * 
	 * @throws CustomException
	 */
	@Override
	public Result<Map<String, Object>> addOrModityRedPacketRule(AddRedPacketRuleVo addRedPacketRuleVo)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, CustomException {
		Result<Map<String, Object>> res = new Result<Map<String, Object>>();
		RuleSet rs = new RuleSet();
		PropertyUtils.copyProperties(rs, addRedPacketRuleVo);
		rs.setRuleType(RuleType.RED_PACKET.toString());
		// rs.setDrawUrl(null);
		// id 为空是新增 否则就是修改
		if (addRedPacketRuleVo.getId() != null) {
			RuleSet ruleSet = ruleSetMapper.queryRuleSetById(addRedPacketRuleVo.getId());
			if (ruleSet != null) {
				if (!Status.NOT_ACTIVATE.toString().equals(ruleSet.getStatus())) {
					throw new CustomException(ErrorCode.RULE_NOT_MODITY.getCode(), "只有在待激活状态下才能修改");
				}
				rs.setUseNum(ruleSet.getUseNum());
				rs.setSerialNumber(ruleSet.getSerialNumber());
				rs.setCreateId(ruleSet.getCreateId());
				rs.setSysId(ruleSet.getSysId());
				rs.setStatus(ruleSet.getStatus());
				rs.setDelFlag(ruleSet.getDelFlag());
				rs.setCreateTime(ruleSet.getCreateTime());
				ruleSetMapper.updateByPrimaryKey(rs);
				res.setErrorCode(ErrorCode.SUCCESS);
				// res.setData(rs);
			} else {
				throw new CustomException(ErrorCode.RULE_NULL.getCode(), "查无规则");
			}
		} else {
			// 新增
			rs.setUseNum(0);
			rs.setSerialNumber(CommonUtils.getUUID());
			rs.setStatus(Status.NOT_ACTIVATE.toString());
			rs.setUpdateId(rs.getCreateId());
			ruleSetMapper.insertSelective(rs);
			res.setErrorCode(ErrorCode.SUCCESS);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", rs.getId());
			res.setData(map);
		}
		return res;
	}
	
	/**
	 * 查询红包规则
	 * 
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	@Override
	public PageResult<List<RuleListResponseVo>> findRedRuleList(RuleSet rs, Integer pageNumber, Integer pageSize, String orderBy, String sort)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		rs.setRuleType(RuleType.RED_PACKET.toString());
		PageHelper.startPage(pageNumber, pageSize);
		List<RuleSet> redRuleList = ruleSetMapper.findRuleList(rs, orderBy, sort);
		PageInfo<RuleSet> page = new PageInfo<>(redRuleList);
		PageResult<List<RuleListResponseVo>> pageObjectVo = new PageResult<>();
		List<RuleListResponseVo> volist = new ArrayList<>();
		for (RuleSet temp : redRuleList) {
			RuleListResponseVo vo = new RuleListResponseVo();
			PropertyUtils.copyProperties(vo, temp);
			volist.add(vo);
		}
		pageObjectVo.setData(volist);
		pageObjectVo.setTotal_record(Integer.valueOf(page.getTotal() + ""));
		pageObjectVo.setErrorCode(ErrorCode.SUCCESS);
		return pageObjectVo;
	}
	
	/**
	 * 根据Id查询红包规则
	 */
	@Override
	public RuleSet findRuleById(Long id) {
		RuleSet ruleSet = ruleSetMapper.queryRuleSetById(id);
		return ruleSet;
	}
	
	/**
	 * 根据id更新
	 * 
	 * @param rs
	 */
	public void updateById(RuleSet rs) {
		ruleSetMapper.updateByPrimaryKeySelective(rs);
	}
	
	/**
	 * 修改红包规则的状态
	 */
	@Override
	public Result modityStatusRedRuleById(Long id, Long updateId, String status) throws CustomException {
		RuleSet ruleSet = ruleSetMapper.queryRuleSetById(id);
		if (ruleSet != null) {
			
		} else {
			throw new CustomException(ErrorCode.RULE_NULL.getCode(), "查无规则");
		}
		return null;
	}
	
	/**
	 * 修改规则的状态
	 */
	@Override
	public Result modityStatusRuleById(Long id, Long updateId, String status, Long sysId) throws CustomException {
		RuleSet ruleSet = ruleSetMapper.queryRuleSetById(id);
		if (ruleSet != null && sysId != null && ruleSet.getSysId().equals(sysId)) {
			ruleSet.setUpdateId(updateId);
			String srcStatus = ruleSet.getStatus();// 改变之前的状态
			ruleSet.setStatus(status);
			if (Status.ALR_ENABLE.toString().equals(status)) {
				if (!(Status.NOT_ACTIVATE.toString().equals(srcStatus) || Status.ALR_DISABLE.toString().equals(srcStatus))) {
					throw new CustomException(ErrorCode.RULE_NOT_MODITY_STATUS.getCode(), "只有在待激活或禁用状态下才能激活或启用");
				} else {
					ruleSet.setEnableId(updateId);
					ruleSet.setEnableTime(DateUtils.getCurrentDateTime());
					// 判断是不是红包规则
					if (RuleType.RED_PACKET.toString().equals(ruleSet.getRuleType())) {
						
						doRedPacketStatus(ruleSet, srcStatus);
					}
				}
			} else if (Status.ALR_DISABLE.toString().equals(status)) {
				if (!(Status.ALR_ENABLE.toString().equals(srcStatus))) {
					throw new CustomException(ErrorCode.RULE_NOT_MODITY_STATUS.getCode(), "只有在已激活或启用状态下才能禁用");
				} else {
					ruleSet.setDisableId(updateId);
					ruleSet.setDisableTime(DateUtils.getCurrentDateTime());
					// 判断是不是红包规则
					// if (RuleType.RED_PACKET.toString().equals(ruleSet.getRuleType())) {
					// doRedPacketStatus(ruleSet, srcStatus);
					// }
				}
			}
			ruleSetMapper.updateByPrimaryKeySelective(ruleSet);
			
		} else {
			throw new CustomException(ErrorCode.RULE_NULL.getCode(), "查无规则");
		}
		Result res = new Result();
		return res;
	}
	
	/**
	 * 新增特价规则
	 * 
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws CustomException
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<Map<String, Object>> addOrModitySpecialRule(AddSpecialRuleVo addSpecialRuleVo)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, CustomException {
		Result<Map<String, Object>> res = new Result<>();
		RuleSet rs = new RuleSet();
		PropertyUtils.copyProperties(rs, addSpecialRuleVo);
		rs.setRuleType(RuleType.SPECIAL_PRICE.toString());
		rs.setShowType(ShowType.SPECIAL_PRICE + "");
		if (addSpecialRuleVo.getId() != null) {
			// 修改
			RuleSet ruleSet = ruleSetMapper.queryRuleSetById(addSpecialRuleVo.getId());
			if (ruleSet != null) {
				if (!Status.NOT_ACTIVATE.toString().equals(ruleSet.getStatus())) {
					throw new CustomException(ErrorCode.RULE_NOT_MODITY.getCode(), "只有在待激活状态下才能修改");
				} else {
					rs.setCreateId(ruleSet.getCreateId());
					rs.setSysId(ruleSet.getSysId());
					rs.setStatus(ruleSet.getStatus());
					rs.setCreateTime(ruleSet.getCreateTime());
					rs.setDelFlag(ruleSet.getDelFlag());
					ruleSetMapper.updateByPrimaryKey(rs);
				}
			} else {
				throw new CustomException(ErrorCode.RULE_NULL.getCode(), "查无规则");
			}
		} else {
			// 新增
			rs.setStatus(Status.NOT_ACTIVATE.toString());
			rs.setUpdateId(rs.getCreateId());
			ruleSetMapper.insertSelective(rs);
		}
		
		if (!(addSpecialRuleVo.getProRuleList() != null && addSpecialRuleVo.getProRuleList().size() > 0)) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "特价规则商品信息为空");
		}
		
		// 修改的话 现将所有的商品信息删掉 重新插入
		if (addSpecialRuleVo.getId() != null) {
			/*
			 * List<Long> ids = new ArrayList<>(); for (ProRuleSet prs : addSpecialRuleVo.getProRuleList()) { if (prs.getId() != null) { ids.add(prs.getId()); } else { throw new
			 * CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "商品信息的Id不能为空"); } }
			 */
			proRuleSetMapper.delProRuleSetByRuleId(rs.getId());
		}
		List<ProRuleSet> proList = new ArrayList<>();
		// 保存商品信息
		for (ProRuleSet prs : addSpecialRuleVo.getProRuleList()) {
			// 先查是改sku是否存在其他的规则中
			if (StringUtil.isNotBlank(prs.getProSku())) {
				ProRuleSet tempRule = proRuleSetMapper.findBySkuAndRuleSetId(rs.getId(), prs.getProSku());
				if (tempRule != null) {
					throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "参数sku不能重复");
				}
				prs.setRuleSetId(rs.getId());
				proRuleSetMapper.insertSelective(prs);
				proList.add(prs);
				// } else {
				// //改sku存在其他的规则 --覆盖
				// for (ProRuleSet ps : tempRule) {
				// ps.setRuleSetId(rs.getId());
				// ps.setSpecialPrice(prs.getSpecialPrice());
				// ps.setSubAmount(prs.getSubAmount());
				// ps.setDiscount(prs.getDiscount());
				// proRuleSetMapper.updateByPrimaryKeySelective(ps);
				// proList.add(ps);
				// }
				// }
			} else {
				throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "参数sku不能为空");
			}
		}
		rs.setProRuleList(proList);
		res.setErrorCode(ErrorCode.SUCCESS);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", rs.getId());
		res.setData(map);
		// res.setData(rs);
		return res;
	}
	
	/**
	 * 查询规则列表
	 * 
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	@Override
	public PageResult<List<RuleListResponseVo>> findRuleList(RuleSet rs, Integer pageNumber, Integer pageSize, String orderBy, String sort)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		String[] showType = new String[] { ShowType.SPECIAL_PRICE.toString() };
		
		List<RuleSet> redRuleList = null;
		PageHelper.startPage(pageNumber, pageSize);
		if (RuleType.SPECIAL_PRICE.toString().equals(rs.getRuleType())) {
			redRuleList = ruleSetMapper.findSpecialRuleList(rs, orderBy, sort, rs.getSku());
		} else if (RuleType.CART.toString().equals(rs.getRuleType())) {
			redRuleList = ruleSetMapper.findRuleList(rs, orderBy, sort);
		} else if (RuleType.DRAW.toString().equals(rs.getRuleType())) {
			redRuleList = ruleSetMapper.findRuleList(rs, orderBy, sort);
		} else if (RuleType.USER_BEHAVIOR.toString().equals(rs.getRuleType())) {
			redRuleList = ruleSetMapper.findRuleList(rs, orderBy, sort);
		}
		List<RuleListResponseVo> volist = new ArrayList<>();
		// 为列表设置 激活人的名称和创建的名称
		if (redRuleList != null && redRuleList.size() > 0) {
			List<Long> sysUserId = new ArrayList<>();
			for (RuleSet temprs : redRuleList) {
				sysUserId.add(temprs.getCreateId());
				sysUserId.add(temprs.getEnableId());
			}
			List<SysUser> sysUsers = sysUserService.findByIds(sysUserId);
			Map<Long, SysUser> sysUserMap = new HashMap<>();
			for (SysUser mem : sysUsers) {
				sysUserMap.put(mem.getId(), mem);
			}
			for (RuleSet temprs : redRuleList) {
				SysUser cmem = sysUserMap.get(temprs.getCreateId());
				SysUser emem = sysUserMap.get(temprs.getEnableId());
				if (cmem != null) {
					temprs.setCreateName(cmem.getRealName());
				}
				if (emem != null) {
					temprs.setEnableName(emem.getRealName());
				}
			}
			for (RuleSet temp : redRuleList) {
				RuleListResponseVo vo = new RuleListResponseVo();
				PropertyUtils.copyProperties(vo, temp);
				volist.add(vo);
			}
		}
		PageInfo<RuleSet> page = new PageInfo<>(redRuleList);
		PageResult<List<RuleListResponseVo>> pageObjectVo = new PageResult<List<RuleListResponseVo>>();
		pageObjectVo.setData(volist);
		pageObjectVo.setTotal_record(Integer.valueOf(page.getTotal() + ""));
		pageObjectVo.setErrorCode(ErrorCode.SUCCESS);
		return pageObjectVo;
	}
	
	/**
	 * 查询特价详情
	 * 
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	@Override
	public AddSpecialRuleVo findSpecialRuleDetailById(Long id, Long sysId) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		RuleSet ruleSet = ruleSetMapper.queryRuleSetById(id);
		if (ruleSet != null && RuleType.SPECIAL_PRICE.toString().equals(ruleSet.getRuleType()) && sysId.equals(ruleSet.getSysId())) {
			List<ProRuleSet> pros = proRuleSetMapper.querySpecialPriceProByRuleId(ruleSet.getId());
			// List<String> skuList = new ArrayList<>();
			// 拼接sku
			AddSpecialRuleVo vo = new AddSpecialRuleVo();
			PropertyUtils.copyProperties(vo, ruleSet);
			StringBuilder proSkuBuilder = new StringBuilder();
			String sp = "";
			for (ProRuleSet p : pros) {
				p.getProSku();
				// skuList.add(p.getProSku());
				proSkuBuilder.append(sp);
				proSkuBuilder.append("'");
				proSkuBuilder.append(p.getProSku());
				proSkuBuilder.append("'");
				sp = ",";
				
			}
			JSONObject params = new JSONObject();
			params.put("sysId", sysId);
			params.put("proSkus", proSkuBuilder.toString());
			// 给商品设置名称及价格
			List<ProVo> proVoList = productInfoService.findPro(params, null);
			Map<String, ProVo> map = new HashMap<>();
			for (ProVo proVo : proVoList) {
				map.put(proVo.getProSku(), proVo);
			}
			
			for (ProRuleSet ps : pros) {
				if (map.get(ps.getProSku()) != null) {
					ps.setPrice(map.get(ps.getProSku()).getPrice());
					ps.setProName(map.get(ps.getProSku()).getProName());
				}
				
			}
			vo.setProRuleList(pros);
			return vo;
		}
		return null;
		
	}
	
	/**
	 * 新增、修改购物车规则
	 * 
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws CustomException
	 */
	@Override
	public Result<Map<String, Object>> addOrModityCartRule(AddCartRuleVo addCartRule)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, CustomException {
		
		Result<Map<String, Object>> res = new Result<>();
		RuleSet rs = new RuleSet();
		PropertyUtils.copyProperties(rs, addCartRule);
		rs.setRuleType(RuleType.CART.toString());
		// id 为空是新增 否则就是修改
		if (addCartRule.getId() != null) {
			RuleSet ruleSet = ruleSetMapper.queryRuleSetById(addCartRule.getId());
			if (ruleSet != null) {
				if (!Status.NOT_ACTIVATE.toString().equals(ruleSet.getStatus())) {
					throw new CustomException(ErrorCode.RULE_NOT_MODITY.getCode(), "只有在待激活状态下才能修改");
				}
				rs.setCreateId(ruleSet.getCreateId());
				rs.setSysId(ruleSet.getSysId());
				rs.setStatus(ruleSet.getStatus());
				rs.setDelFlag(ruleSet.getDelFlag());
				rs.setCreateTime(ruleSet.getCreateTime());
				ruleSetMapper.updateByPrimaryKey(rs);
				res.setErrorCode(ErrorCode.SUCCESS);
				// res.setData(rs);
			} else {
				throw new CustomException(ErrorCode.RULE_NULL.getCode(), "查无规则");
			}
		} else {
			// 新增
			rs.setStatus(Status.NOT_ACTIVATE.toString());
			rs.setUpdateId(rs.getCreateId());
			ruleSetMapper.insertSelective(rs);
			res.setErrorCode(ErrorCode.SUCCESS);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", rs.getId());
			res.setData(map);
		}
		return res;
	}
	
	@Override
	public Result<Map<String, Object>> addOrModityDrawRule(AddDrawRuleVo addDrawRuleVo)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, CustomException {
		Result<Map<String, Object>> res = new Result<>();
		RuleSet rs = new RuleSet();
		addDrawRuleVo.setSerialNumber(null);// 序列号第一次有系统生成，不能在改
		PropertyUtils.copyProperties(rs, addDrawRuleVo);
		rs.setRuleType(RuleType.DRAW.toString());
		// rs.setShowType(ShowType..toString());
		if (addDrawRuleVo.getId() != null) {
			// 修改
			RuleSet ruleSet = ruleSetMapper.queryRuleSetById(addDrawRuleVo.getId());
			if (ruleSet != null) {
				if (!Status.NOT_ACTIVATE.toString().equals(ruleSet.getStatus())) {
					throw new CustomException(ErrorCode.RULE_NOT_MODITY.getCode(), "只有在待激活状态下才能修改");
				} else {
					rs.setSerialNumber(ruleSet.getSerialNumber());
					rs.setCreateId(ruleSet.getCreateId());
					rs.setSysId(ruleSet.getSysId());
					rs.setStatus(ruleSet.getStatus());
					rs.setDelFlag(ruleSet.getDelFlag());
					rs.setCreateTime(ruleSet.getCreateTime());
					ruleSetMapper.updateByPrimaryKey(rs);
				}
			} else {
				throw new CustomException(ErrorCode.RULE_NULL.getCode(), "查无规则");
			}
		} else {
			// 新增
			rs.setStatus(Status.NOT_ACTIVATE.toString());
			rs.setUpdateId(rs.getCreateId());
			rs.setSerialNumber(CommonUtils.getUUID());
			ruleSetMapper.insertSelective(rs);
		}
		
		// 修改的话将 等级及奖品信息删除
		if (addDrawRuleVo.getId() != null) {
			prizeMapper.delAllByRuleId(addDrawRuleVo.getId());
			drawLevelGroupMapper.delAllByRuleId(addDrawRuleVo.getId());
		}
		// 保存 等级及奖品信息
		if (addDrawRuleVo.getDrawLevelGroups() != null) {
			for (DrawLevelGroupVo levelGroup : addDrawRuleVo.getDrawLevelGroups()) {
				DrawLevelGroup dlg = new DrawLevelGroup();
				PropertyUtils.copyProperties(dlg, levelGroup);
				dlg.setRuleId(rs.getId());
				dlg.setCreateId(rs.getCreateId());
				dlg.setUpdateId(rs.getUpdateId());
				drawLevelGroupMapper.insertSelective(dlg);
				if (levelGroup.getPrizes() != null) {
					for (Prize pvo : levelGroup.getPrizes()) {
						pvo.setRuleId(rs.getId());
						pvo.setLevelId(dlg.getId());
						pvo.setCreateId(rs.getCreateId());
						pvo.setUpdateId(rs.getUpdateId());
						if (PrizeType.GIVE_DRAW_NUM.toString().equals(pvo.getPrizeType())) {
							pvo.setPrizeNo(rs.getId() + "");
						}
						prizeMapper.insertSelective(pvo);
					}
				} else {
					throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "参数出错 --奖品信息不能为空");
				}
			}
		} else {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "参数出错 --等级信息不能为空");
		}
		res.setErrorCode(ErrorCode.SUCCESS);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", rs.getId());
		
		res.setData(map);
		return res;
	}
	
	@Override
	public AddDrawRuleVo findDrawRuleById(Long id, Long sysId) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		AddDrawRuleVo addDrawRuleVo = new AddDrawRuleVo();
		RuleSet ruleSet = ruleSetMapper.queryRuleSetById(id);
		if (ruleSet != null && RuleType.DRAW.toString().equals(ruleSet.getRuleType()) && sysId.equals(ruleSet.getSysId())) {
			DrawLevelGroup tempGroup = new DrawLevelGroup();
			tempGroup.setRuleId(ruleSet.getId());
			List<DrawLevelGroup> drawLevelGroups = drawLevelGroupMapper.findAllDrawLevelGroup(tempGroup);
			List<Long> groupIds = new ArrayList<>();
			// 拼接等级分组Id 查询奖品信息
			for (DrawLevelGroup dlg : drawLevelGroups) {
				groupIds.add(dlg.getId());
			}
			List<Prize> prizeList = prizeMapper.findAllPrizeByGroupIds(groupIds);
			// 将奖品信息根据 等级Id分组
			MultiValueMap<Long, Prize> prizeMap = new LinkedMultiValueMap<>();
			for (Prize p : prizeList) {
				prizeMap.add(p.getLevelId(), p);
			}
			List<DrawLevelGroupVo> ruturnDrawLevelGroup = new ArrayList<>();
			for (DrawLevelGroup dlg : drawLevelGroups) {
				DrawLevelGroupVo vo = new DrawLevelGroupVo();
				PropertyUtils.copyProperties(vo, dlg);
				List<Prize> prizes = prizeMap.get(dlg.getId());
				vo.setPrizes(prizes);
				ruturnDrawLevelGroup.add(vo);
			}
			PropertyUtils.copyProperties(addDrawRuleVo, ruleSet);
			addDrawRuleVo.setDrawLevelGroups(ruturnDrawLevelGroup);
			return addDrawRuleVo;
		}
		return null;
	}
	
	/**
	 * 新增，修改用户行为
	 * 
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws CustomException
	 */
	@Override
	public Result<Map<String, Object>> addOrModityUserBehaviorRule(AddUserBehaviorRuleVo addUserBehaviorRuleVo)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, CustomException {
		
		Result<Map<String, Object>> res = new Result<Map<String, Object>>();
		RuleSet rs = new RuleSet();
		PropertyUtils.copyProperties(rs, addUserBehaviorRuleVo);
		rs.setRuleType(RuleType.USER_BEHAVIOR.toString());
		// id 为空是新增 否则就是修改
		if (addUserBehaviorRuleVo.getId() != null) {
			RuleSet ruleSet = ruleSetMapper.queryRuleSetById(addUserBehaviorRuleVo.getId());
			if (ruleSet != null) {
				if (!Status.NOT_ACTIVATE.toString().equals(ruleSet.getStatus())) {
					throw new CustomException(ErrorCode.RULE_NOT_MODITY.getCode(), "只有在待激活状态下才能修改");
				}
				rs.setCreateId(ruleSet.getCreateId());
				rs.setSysId(ruleSet.getSysId());
				rs.setStatus(ruleSet.getStatus());
				rs.setDelFlag(ruleSet.getDelFlag());
				rs.setCreateTime(ruleSet.getCreateTime());
				ruleSetMapper.updateByPrimaryKey(rs);
				res.setErrorCode(ErrorCode.SUCCESS);
				// res.setData(rs);
			} else {
				throw new CustomException(ErrorCode.RULE_NULL.getCode(), "查无规则");
			}
		} else {
			// 新增
			rs.setStatus(Status.NOT_ACTIVATE.toString());
			rs.setUpdateId(rs.getCreateId());
			ruleSetMapper.insertSelective(rs);
			res.setErrorCode(ErrorCode.SUCCESS);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", rs.getId());
			res.setData(map);
		}
		return res;
	}
	
	@Override
	public RuleSet findUserBehaviorRuleById(Long id) {
		return null;
	}
	
	/**
	 * 检验规则是否可用 
	 *
	 * @Title: checkRuleSet 
	 * @author: wuyicheng
	 * @date: 2017年7月20日下午3:43:37 
	 * @param checkRuleSetParam
	 * @return
	 * @throws CustomException
	 * @throws
	 */
	@Override
	public CheckRuleSetResult checkRuleSet(CheckRuleSetParam checkRuleSetParam) throws CustomException {
		CheckRuleSetResult checkRuleSetResult = new CheckRuleSetResult(ErrorCode.EXCEPTION);
		
		// 规则是否激活
		if (checkRuleSetParam == null || checkRuleSetParam.getRuleSet() == null) {
			// throw new CustomException(ErrorCode.RULE_NULL.getCode(), "规则不存在或者规则被禁用");
			checkRuleSetResult.setErrorCode(ErrorCode.RULE_NULL);
			checkRuleSetResult.setIsCanGet(CheckRuleSetResult.NO_0);
			checkRuleSetResult.setIsCanUse(CheckRuleSetResult.NO_0);
			return checkRuleSetResult;
			
		}
		
		if (!Status.ALR_ENABLE.toString().equals(checkRuleSetParam.getRuleSet().getStatus())) {
			checkRuleSetResult.setErrorCode(ErrorCode.RULE_DISABLE);
			checkRuleSetResult.setIsCanGet(CheckRuleSetResult.NO_0);
			checkRuleSetResult.setIsCanUse(CheckRuleSetResult.NO_0);
			return checkRuleSetResult;
		}
		
		// 判断是否是领取
		if (CheckRuleSetParam.GET_0.equals(checkRuleSetParam.getUseOrGet())) {
			
			this.checkRuleByGet(checkRuleSetParam, checkRuleSetResult);
			
		} else if (CheckRuleSetParam.USE_1.equals(checkRuleSetParam.getUseOrGet())) {
			// 使用规则
			this.checkRuleByUse(checkRuleSetParam, checkRuleSetResult);
			
		}
		
		return checkRuleSetResult;
	}
	
	/**
	 * 使用规则校验
	 *
	 * @Title: checkRuleByUse 
	 * @author: wuyicheng
	 * @date: 2017年7月11日下午4:43:53 
	 * @param checkRuleSetParam
	 * @param checkRuleSetResult
	 * @return
	 * @return: CheckRuleSetResult
	 * @throws
	 */
	private CheckRuleSetResult checkRuleByUse(CheckRuleSetParam checkRuleSetParam, CheckRuleSetResult checkRuleSetResult) {
		RuleSet ruleSet = checkRuleSetParam.getRuleSet();
		checkRuleSetResult.setIsCanUse(CheckRuleSetResult.NO_0);
		
		/****************** 有效期 系统 设备 限制  ↓ ***************************/
		// 红包规则不判断有效期
		if (!(RuleType.RED_PACKET.toString().equals(ruleSet.getRuleType()))) {
			// 判断是否在有效期内
			boolean isOverdue = isOverdue(ruleSet.getStartTime(), ruleSet.getEndTime(), checkRuleSetParam.getCurrentTime());
			if (isOverdue) {
				checkRuleSetResult.setErrorCode(ErrorCode.RULE_ARE_OUTDATED);
				return checkRuleSetResult;
			}
		}
		
		// 系统限制
		if (!ruleSet.getSysId().equals(checkRuleSetParam.getSysId())) {
			checkRuleSetResult.setErrorCode(ErrorCode.RULE_SYSTEM_RESTRICTION);
			return checkRuleSetResult;
		}
		
		// 设备限制PC，WAP
		if (ruleSet.getDevice() != null && checkRuleSetParam.getDevice() != null && ruleSet.getDevice().indexOf(checkRuleSetParam.getDevice()) == -1) {
			checkRuleSetResult.setErrorCode(ErrorCode.RULE_DEVICE_RESTRICTION);
			return checkRuleSetResult;
		}
		
		/****************** 有效期 系统 设备 等级限制  ↑ ***************************/
		
		/****************** 特价规则 限购一单 一单限购数量 是否允许使用优惠券  ↓ ***************************/
		// 特价规则
		if (ShowType.SPECIAL_PRICE.toString().equals(ruleSet.getShowType()) && RuleType.SPECIAL_PRICE.toString().equals(ruleSet.getRuleType())) {
			// 1.限购一单
			if (RuleSet.YES.equals(ruleSet.getIsLimitBuyBill())) {
				// 使用次数是否超出限制
				boolean isBeyond = this.isBeyondRuleLimitUseNums(checkRuleSetParam.getMemberId(), checkRuleSetParam.getSysId(), checkRuleSetParam.getProSku(), ruleSet.getId(),
						ruleSet.getStartTime(), ruleSet.getEndTime(), ruleSet.getLimitBuyBill() == null ? 0 : ruleSet.getLimitBuyBill());
				if (isBeyond) {
					checkRuleSetResult.setErrorCode(ErrorCode.RULE_BEYOND_LIMIT_BILL);
					return checkRuleSetResult;
				}
			}
			
			// 2.一单限购数量
			/*			if (RuleSet.YES.equals(ruleSet.getIsLimitBuyNum()) && (ArithUtil.compareTo(checkRuleSetParam.getBuyNums(), ruleSet.getNumDown()) < 0
								|| ArithUtil.compareTo(checkRuleSetParam.getBuyNums(), ruleSet.getNumTop()) > 0)) {
							checkRuleSetResult.setErrorCode(ErrorCode.RULE_BEYOND_LIMIT_NUM);
							return checkRuleSetResult;
						}*/
			if (RuleSet.YES.equals(ruleSet.getIsLimitBuyNum())) {
				
				if (ruleSet.getNumDown() != null && ArithUtil.compareTo(checkRuleSetParam.getBuyNums(), ruleSet.getNumDown()) < 0) {
					checkRuleSetResult.setErrorCode(ErrorCode.RULE_BEYOND_LIMIT_NUM);
					return checkRuleSetResult;
				}
				
				if (ruleSet.getNumTop() != null && ArithUtil.compareTo(checkRuleSetParam.getBuyNums(), ruleSet.getNumTop()) > 0) {
					checkRuleSetResult.setErrorCode(ErrorCode.RULE_BEYOND_LIMIT_NUM);
					return checkRuleSetResult;
				}
				
			}
			
			// 3.是否禁用使用优惠券
			if (RuleSet.YES.equals(ruleSet.getIsStopPrivilege())) {
				checkRuleSetResult.setIsDisableRedpacket(CheckRuleSetResult.IS_DISABLE_YES_1);
			}
			
			// 4.是否限制等级
			MemberLevel memberLevel = memberLevelService.findByMemberIdAndSysId(checkRuleSetParam.getMemberId(), checkRuleSetParam.getSysId());
			// 会员等级是否可用
			boolean isCanUseMemberLevel = this.checkLimitMemberLevel(memberLevel, ruleSet);
			// 符合等级限制
			if (!isCanUseMemberLevel) {
				// 会员等级
				checkRuleSetResult.setErrorCode(ErrorCode.LEVEL_IS_NOT_GET);
				return checkRuleSetResult;
			}
			
		}
		/****************** 特价规则 限购一单 一单限购数量 是否允许使用优惠券  ↑ ***************************/
		
		/****************** 红包规则 商品限制 商品满用金额限制  ↓ ***************************/
		// 红包规则
		if (RuleType.RED_PACKET.toString().equals(ruleSet.getRuleType())) {
			
			// 商品限制
			Map<String, BigDecimal> limitProMap = this.getLimitPro(checkRuleSetParam.getShoppingCartList(), ruleSet);
			if (limitProMap == null || limitProMap.size() <= 0) {
				checkRuleSetResult.setErrorCode(ErrorCode.RULE_LIMIT_PRO_NULL);
				return checkRuleSetResult;
			}
			BigDecimal totalAmount = limitProMap.get("totalAmount");// 总金额
			
			// 商品满用金额限制 商品总金额 < 满送金额
			if (ArithUtil.compareTo(totalAmount, ruleSet.getFullAmountUse()) < 0) {
				checkRuleSetResult.setErrorCode(ErrorCode.RULE_NOT_SARISFY);
				return checkRuleSetResult;
			}
			
			checkRuleSetResult.setLimitProMap(limitProMap);
			
		}
		/****************** 红包规则 商品限制 商品满用金额限制  ↑ ***************************/
		
		/****************** 购物车规则 客户参与次数限制 是否停用优惠券 商品 购买金额 ↓ ***************************/
		// 购物车规则
		if (RuleType.CART.toString().equals(ruleSet.getRuleType())) {
			
			// 是否限制等级
			MemberLevel memberLevel = memberLevelService.findByMemberIdAndSysId(checkRuleSetParam.getMemberId(), checkRuleSetParam.getSysId());
			// 会员等级是否可用
			boolean isCanUseMemberLevel = this.checkLimitMemberLevel(memberLevel, ruleSet);
			// 符合等级限制
			if (!isCanUseMemberLevel) {
				// 会员等级
				checkRuleSetResult.setErrorCode(ErrorCode.LEVEL_IS_NOT_GET);
				return checkRuleSetResult;
			}
			
			// 客户参与次数限制
			if (ruleSet.getJoinNum() != null) {
				// 是否超出限制次数
				boolean isBeyond = this.isBeyondRuleLimitUseNums(checkRuleSetParam.getMemberId(), checkRuleSetParam.getSysId(), null, ruleSet.getId(), ruleSet.getStartTime(),
						ruleSet.getEndTime(), ruleSet.getJoinNum());
				if (isBeyond) {
					checkRuleSetResult.setErrorCode(ErrorCode.RULE_BEYOND_LIMIT_NUM);
					return checkRuleSetResult;
				}
			}
			
			// 是否停用优惠券
			if (RuleSet.YES.equals(ruleSet.getIsStopPrivilege())) {
				checkRuleSetResult.setIsDisableRedpacket(CheckRuleSetResult.IS_DISABLE_YES_1);
				// 如果选择了红包，就移除排斥红包的规则
				if (checkRuleSetParam.getUseRedPacketId() != null) {
					checkRuleSetResult.setErrorCode(ErrorCode.RUEL_CONDLICT_REDPACKET);
					return checkRuleSetResult;
				}
			}
			
			// 统计符合限制商品小计
			Map<String, BigDecimal> limitProMap = this.getLimitPro(checkRuleSetParam.getShoppingCartList(), ruleSet);
			// 判断商品是否符合规则
			if (limitProMap == null || limitProMap.size() <= 0) {
				checkRuleSetResult.setErrorCode(ErrorCode.RULE_LIMIT_PRO_NULL);
				return checkRuleSetResult;
			}
			BigDecimal totalNums = limitProMap.get("totalNums");// 总数量
			BigDecimal totalAmount = limitProMap.get("totalAmount");// 总金额
			
			// 判断是否满足限制金额和数量
			boolean isCanUse = this.isCanUseRuleSet(ruleSet, totalNums, totalAmount);
			// 不符合限制规则
			if (!isCanUse) {
				checkRuleSetResult.setErrorCode(ErrorCode.RULE_NOT_SARISFY);
				return checkRuleSetResult;
			}
			
			checkRuleSetResult.setLimitProMap(limitProMap);
			
			// 免邮条件
			if (ShowType.FREE_POSTAGE.toString().equals(ruleSet.getShowType())) {
				// 快递编码!=客服所选
				if (checkRuleSetParam.getDeliveryMethodCode() == null) {
					checkRuleSetResult.setErrorCode(ErrorCode.FREE_POSTAGE_CONDIRION_FALSE);
					return checkRuleSetResult;
				}
				
				// 支付类型!=客服所选
				if (checkRuleSetParam.getPayMethodCode() == null) {
					checkRuleSetResult.setErrorCode(ErrorCode.FREE_POSTAGE_CONDIRION_FALSE);
					return checkRuleSetResult;
				}
				
			}
			
		}
		/****************** 购物车规则 客户参与次数限制 是否停用优惠券 商品 购买金额 ↑ ***************************/
		
		checkRuleSetResult.setErrorCode(ErrorCode.SUCCESS);
		checkRuleSetResult.setIsCanUse(CheckRuleSetResult.YES_1);
		return checkRuleSetResult;
		
	}
	
	/**
	 * 获取满足限制的商品
	 *
	 * @Title: getLimitPro 
	 * @author: wuyicheng
	 * @date: 2017年7月20日下午6:21:33 
	 * @param shoppingCartList
	 * @param ruleSet
	 * @return
	 * @return: Map<String,BigDecimal>
	 * @throws
	 */
	private Map<String, BigDecimal> getLimitPro(List<ShoppingCart> shoppingCartList, RuleSet ruleSet) {
		Map<String, BigDecimal> limitProMap = new HashMap<>();
		BigDecimal totalNums = new BigDecimal(0);// 总数量
		BigDecimal totalAmount = new BigDecimal(0);// 总金额
		String maxProSku = "";// 获取小计最大值
		BigDecimal maxAmount = new BigDecimal(0.00);// 最大小计
		// 查询可使用商品
		for (ShoppingCart shoppingCart : shoppingCartList) {
			// 购物车赠品不参与规则
			if (ShoppingCart.PREMIUM_YES.equals(shoppingCart.getIsPremium())) {
				continue;
			}
			
			// 购物车的积分商品不参与规则
			if (ShoppingCart.INTEGRAL_PRO_YES_1.equals(shoppingCart.getIsIntegralPro())) {
				continue;
			}
			// 验证商品是否符合使用
			// 是否限制商品
			if (ProTypeLimit.LIMIT_PRO.toString().equals(ruleSet.getProTypeLimit())) {
				ProductInfo productInfo = productInfoService.getProBySku(shoppingCart.getProSku());
				// 品牌
				// 品类类型不为空
				if (StringUtil.isNotBlank(ruleSet.getBrandType())) {
					
					// 条件属于品牌，
					if (RuleSet.YES.equals(ruleSet.getIsBrandJoin())) {
						
						// 不属于这个品牌，跳过
						if (productInfo.getBrandId() == null) {
							continue;
						}
						
						// 不属于这个品牌，跳过
						if (!(StringUtil.isContains(productInfo.getBrandId().toString(), ruleSet.getBrandType(), ConstantsUtil.COMMA))) {
							continue;
						}
						
					} else if (RuleSet.NO.equals(ruleSet.getIsBrandJoin())) {
						// 条件不属于品牌，
						// 当前商品属于，跳过
						if (productInfo.getBrandId() != null && StringUtil.isContains(productInfo.getBrandId().toString(), ruleSet.getBrandType(), ConstantsUtil.COMMA)) {
							continue;
						}
					} // 品牌限制end
				}
				
				// 品类
				// 品类类型不空
				if (StringUtil.isNotBlank(ruleSet.getCatType())) {
					
					// 条件属于品类，当前商品属于
					if (RuleSet.YES.equals(ruleSet.getIsCatJoin())) {
						
						// 不属于这个品类，跳过
						if (productInfo.getCatId() == null) {
							continue;
						}
						
						// 当前商品不属于，跳过
						if (!(StringUtil.isContains(productInfo.getCatId().toString(), ruleSet.getCatType(), ConstantsUtil.COMMA))) {
							continue;
						}
						
					} else if (RuleSet.NO.equals(ruleSet.getIsCatJoin())) {
						
						// 条件不属于品类，当前商品属于
						
						// 当前商品属于，跳过
						if (productInfo.getCatId() != null && StringUtil.isContains(productInfo.getCatId().toString(), ruleSet.getCatType(), ConstantsUtil.COMMA)) {
							continue;
						}
					}
					
				} // 品类限制end
				
				// SKU限制
				if (!(RuleSet.SKU_INCLUDE_NO_LIMIT.equals(ruleSet.getIsSkuJoin())) && StringUtil.isNotBlank(ruleSet.getSku())) {
					// 规则SKU是否存在当前商品
					boolean isContains = StringUtil.isContains(shoppingCart.getProSku(), ruleSet.getSku(), ConstantsUtil.COMMA);
					
					// 条件不属于SKU，存在属于，跳过
					if (RuleSet.SKU_INCLUDE_NO.equals(ruleSet.getIsSkuJoin()) && isContains) {
						continue;
					}
					
					// 条件属于SKU，存在不属于，跳过
					if (RuleSet.SKU_INCLUDE_YES.equals(ruleSet.getIsSkuJoin()) && !isContains) {
						continue;
					}
					
				} // SKU限制end
				
			} // 商品限制end
			
			// 单品折扣获取只取符合的第一个商品
			if (ShowType.SINGLE_PRO_DISCOUNT.toString().equals(ruleSet.getShowType())) {
				
				// 如果小计小于满用 则跳过
				if (ArithUtil.compareTo(shoppingCart.getActualPaySubtotal(), ruleSet.getFullAmountUse()) < 0) {
					continue;
				}
				
				// 当前商品小计是否最大
				if (StringUtil.isNotBlank(maxProSku)) {
					// 当前商品小计是否最大 &&
					if (ArithUtil.compareTo(maxAmount, shoppingCart.getActualPaySubtotal()) < 0) {
						maxProSku = shoppingCart.getProSku();
						maxAmount = shoppingCart.getActualPaySubtotal();
						totalNums = new BigDecimal(shoppingCart.getBuyNum());
						totalAmount = shoppingCart.getActualPaySubtotal();
					}
				} else {
					maxProSku = shoppingCart.getProSku();
					maxAmount = shoppingCart.getActualPaySubtotal();
					totalNums = new BigDecimal(shoppingCart.getBuyNum());
					totalAmount = shoppingCart.getActualPaySubtotal();
				}
			} else {
				// 非单品折扣 统计所有符合商品
				totalNums = ArithUtil.add(totalNums, new BigDecimal(shoppingCart.getBuyNum()), 2);
				totalAmount = ArithUtil.add(totalAmount, shoppingCart.getActualPaySubtotal(), 2);
				limitProMap.put(shoppingCart.getProSku(), shoppingCart.getActualPaySubtotal());
			}
		}
		
		// 单品折扣商品放入
		if (ShowType.SINGLE_PRO_DISCOUNT.toString().equals(ruleSet.getShowType()) && StringUtil.isNotBlank(maxProSku)) {
			limitProMap.put(maxProSku, maxAmount);
		}
		
		if (limitProMap != null && limitProMap.size() > 0) {
			limitProMap.put("totalNums", totalNums);
			limitProMap.put("totalAmount", totalAmount);
		}
		
		return limitProMap;
	}
	
	/** 
	 * 判断是否满足限制金额和数量
	 * 
	 * @Title: isCanUseRuleSet 
	 * @author: wuyicheng
	 * @date: 2017年7月18日下午3:31:26 
	 * @param ruleSet
	 * @param totalNums
	 * @param totalAmount
	 * @return
	 * @return: boolean
	 * @throws 
	 */
	private boolean isCanUseRuleSet(RuleSet ruleSet, BigDecimal totalNums, BigDecimal totalAmount) {
		boolean flag = true;
		if (RuleSet.YES.equals(ruleSet.getIsLimitBuyMoney())) {
			// 限制金额 大于等于X，小于X
			if (ruleSet.getAmountDown() != null && ArithUtil.compareTo(totalAmount, ruleSet.getAmountDown()) < 0) {
				flag = false;
			}
			if (ruleSet.getAmountTop() != null && ArithUtil.compareTo(totalAmount, ruleSet.getAmountTop()) >= 0) {
				flag = false;
			}
		} else if (RuleSet.YES.equals(ruleSet.getIsLimitBuyNum())) {
			// 限制数量 大于等于X，小于X
			if (ruleSet.getNumDown() != null && ArithUtil.compareTo(totalNums, ruleSet.getNumDown()) < 0) {
				flag = false;
			}
			if (ruleSet.getNumTop() != null && ArithUtil.compareTo(totalNums, ruleSet.getNumTop()) >= 0) {
				flag = false;
			}
		}
		return flag;
	}
	
	/** 
	 * 是否超出规则限制的使用次数
	 *  
	 * @Title: isBeyondRuleLimitUseNums 
	 * @author: wuyicheng
	 * @date: 2017年7月18日上午11:24:17 
	 * @param memberId 会员ID
	 * @param sysId 系统ID
	 * @param proSku 商品SKU
	 * @param ruleSetId 规则ID
	 * @param startTime 规则开始时间
	 * @param endTime 规则结束时间
	 * @param limitNums 限制数量
	 * @return
	 * @return: boolean
	 * @throws 
	 */
	private boolean isBeyondRuleLimitUseNums(Long memberId, Long sysId, String proSku, Long ruleSetId, String startTime, String endTime, int limitNums) {
		Map<String, Object> map = new HashMap<>();
		map.put("memberId", memberId);
		map.put("sysId", sysId);
		if (StringUtil.isNotBlank(proSku)) {
			map.put("proSku", proSku);
		}
		map.put("ruleSetId", ruleSetId);
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		int countUseNums = ruleSetUseLogMapper.countUseNums(map);
		if (countUseNums >= limitNums) {
			return true;
		}
		return false;
	}
	
	/**
	 * 领取规则校验
	 *
	 * @Title: checkRuleByGet 
	 * @author: wuyicheng
	 * @date: 2017年7月12日上午9:50:33 
	 * @param checkRuleSetParam
	 * @param checkRuleSetResult
	 * @return
	 * @return: CheckRuleSetResult
	 * @throws
	 */
	private CheckRuleSetResult checkRuleByGet(CheckRuleSetParam checkRuleSetParam, CheckRuleSetResult checkRuleSetResult) {
		RuleSet ruleSet = checkRuleSetParam.getRuleSet();
		checkRuleSetResult.setIsCanGet(CheckRuleSetResult.NO_0);
		// 红包规则使用条件
		if (RuleType.RED_PACKET.toString().equals(ruleSet.getRuleType())) {
			// 使用数量为空表示0
			if (ruleSet.getUseNum() == null) {
				ruleSet.setUseNum(0);
			}
			// 创建数量为空表示0
			if (ruleSet.getCreateNum() == null) {
				ruleSet.setUseNum(0);
			}
			
			// 使用数量>0
			if (ruleSet.getUseNum().intValue() >= ruleSet.getCreateNum().intValue()) {
				checkRuleSetResult.setErrorCode(ErrorCode.RULE_NO_RED_PACKET);
				checkRuleSetResult.setIsCanUse(CheckRuleSetResult.NO_0);
				return checkRuleSetResult;
			}
			
			// 会员等级空，则不验证 领取数量和等级
			if (checkRuleSetParam.getMemberId() != null) {
				// 是否超出限制领取
				boolean isBeyondLimit = this.isBeyondRedPackLimitGetNums(checkRuleSetParam.getMemberId(), checkRuleSetParam.getSysId(), ruleSet);
				if (isBeyondLimit) {
					checkRuleSetResult.setIsCanGet(CheckRuleSetResult.NO_0);
					checkRuleSetResult.setErrorCode(ErrorCode.RULE_GET_NUM_OUT);
					return checkRuleSetResult;
				}
				
				// 会员等级
				MemberLevel memberLevel = null;
				if (checkRuleSetParam.getMemberLevelId() != null) {
					memberLevel = new MemberLevel();
					memberLevel.setId(checkRuleSetParam.getMemberLevelId());
				} else {
					memberLevel = memberLevelService.findByMemberIdAndSysId(checkRuleSetParam.getMemberId(), checkRuleSetParam.getSysId());
				}
				
				// 会员等级不存在
				if (memberLevel == null || memberLevel.getId() == null) {
					checkRuleSetResult.setIsCanGet(CheckRuleSetResult.NO_0);
					checkRuleSetResult.setErrorCode(ErrorCode.MEMBER_LEVEL_IS_NULL);
					return checkRuleSetResult;
				}
				
				// 会员等级是否可用
				boolean isCanUseMemberLevel = this.checkLimitMemberLevel(memberLevel, ruleSet);
				// 符合等级限制
				if (!isCanUseMemberLevel) {
					// 会员等级
					checkRuleSetResult.setIsCanGet(CheckRuleSetResult.NO_0);
					checkRuleSetResult.setErrorCode(ErrorCode.LEVEL_IS_NOT_GET);
					return checkRuleSetResult;
				}
			}
			
			// 是否错过领券时间
			boolean isOverdue = this.isOverdue(ruleSet.getStartDrawTime(), ruleSet.getEndDrawTime(), checkRuleSetParam.getCurrentTime());
			
			// 是否超出领券时间
			if (isOverdue) {
				checkRuleSetResult.setIsCanGet(CheckRuleSetResult.NO_0);
				checkRuleSetResult.setErrorCode(ErrorCode.RULE_DRAWTIME_OUTDATED);
				return checkRuleSetResult;
			}
			
		}
		checkRuleSetResult.setIsCanGet(CheckRuleSetResult.YES_1);
		checkRuleSetResult.setErrorCode(ErrorCode.SUCCESS);
		return checkRuleSetResult;
		
	}
	
	/**
	 * 会员等级是否符合这个规则
	 *
	 * @Title: checkLimitMemberLevel 
	 * @author: wuyicheng
	 * @date: 2017年7月21日上午9:46:00 
	 * @param memberLevel
	 * @param ruleSet
	 * @return
	 * @throws
	 */
	@Override
	public boolean checkLimitMemberLevel(MemberLevel memberLevel, RuleSet ruleSet) {
		// 是否等级限制 空就是所有等级可以用,非空是等于该等级可用
		if (StringUtil.isNotBlank(ruleSet.getLimitMemberLevel())) {
			String[] memberLevels = ruleSet.getLimitMemberLevel().split(ConstantsUtil.COMMA);
			boolean isConform = false;// 是否符合派发
			// 判断当前规则是否符合等级限制
			if (memberLevels != null && memberLevels.length > 0) {
				for (String level : memberLevels) {
					if (level.equals(String.valueOf(memberLevel.getId()))) {
						isConform = true;
						return true;
					}
				}
				// 不存在可用等级中
				if (!isConform) {
					return false;
				}
			}
			
		}
		return true;
	}
	
	/** 
	 * 是否超出红包限制领取数量
	 * 
	 * @Title: isBeyondRedPackLimitGetNums 
	 * @author: wuyicheng
	 * @date: 2017年7月11日下午6:38:29 
	 * @param memberId 会员ID
	 * @param sysId 系统ID
	 * @param ruleSet 规则
	 * @return
	 * @return: boolean
	 * @throws 
	 */
	private boolean isBeyondRedPackLimitGetNums(Long memberId, Long sysId, RuleSet ruleSet) {
		// 是否限制购买数量
		if (RuleSet.YES.equals(ruleSet.getIsLimitGetNum())) {
			RedPacket redPacket = new RedPacket();
			redPacket.setCreateRuleId(ruleSet.getId());
			redPacket.setMemberId(memberId);
			redPacket.setSysId(sysId);
			// 限制领取数量
			long limitGetNum = ruleSet.getLimitGetNum() == null ? 0 : ruleSet.getLimitGetNum();
			long getNum = redPacketService.countRedPacket(redPacket);
			if (limitGetNum <= getNum) {
				// 超出或等于限制数量不能派发
				return true;
			}
			
		}
		return false;
	}
	
	/**
	 * 是否过期
	 *
	 * @Title: isOverdue 
	 * @author: wuyicheng
	 * @date: 2017年7月31日上午11:54:53 
	 * @param startTime
	 * @param endTime
	 * @param currentTime
	 * @return
	 * @throws
	 */
	@Override
	public boolean isOverdue(String startTime, String endTime, String currentTime) {
		try {
			long currentDate = DateUtils.parseFullTime(currentTime).getTime();
			
			// 判断当前时间
			if (startTime != null) {
				long startDate = DateUtils.parseFullTime(startTime).getTime();
				if (startDate > currentDate) {
					return true;
				}
			}
			
			// 判断当前时间再有效期内
			if (endTime != null) {
				long endDate = DateUtils.parseFullTime(endTime).getTime();
				if (endDate < currentDate) {
					return true;
				}
			}
		} catch (ParseException e) {
			log.info("日期格式异常");
		}
		
		return false;
		
	}
	
	/**
	 * 查询规则列表
	 *
	 * @Title: findList 
	 * @author: wuyicheng
	 * @date: 2017年7月18日下午10:02:27 
	 * @param rs
	 * @param pageNumber
	 * @param pageSize
	 * @param orderBy
	 * @param sort
	 * @return
	 * @throws
	 */
	@Override
	public PageResult<List<RuleListResponseVo>> findList(RuleSet rs, Integer pageNumber, Integer pageSize, String orderBy, String sort) {
		
		PageHelper.startPage(pageNumber, pageSize);
		List<RuleSet> redRuleList = ruleSetMapper.findRuleList(rs, orderBy, sort);
		PageInfo<RuleSet> page = new PageInfo<>(redRuleList);
		PageResult<List<RuleListResponseVo>> pageObjectVo = new PageResult<List<RuleListResponseVo>>();
		List<RuleListResponseVo> volist = new ArrayList<>();
		for (RuleSet temp : redRuleList) {
			RuleListResponseVo vo = new RuleListResponseVo();
			vo.setShowName(temp.getShowName());
			vo.setId(temp.getId());
			volist.add(vo);
		}
		pageObjectVo.setData(volist);
		pageObjectVo.setTotal_record(Integer.valueOf(page.getTotal() + ""));
		pageObjectVo.setErrorCode(ErrorCode.SUCCESS);
		return pageObjectVo;
	}
	
	/**
	 * 红包规则禁用 启用 红包状态的改变
	 * 
	 * @param ruleSet
	 * @throws CustomException 
	 */
	public void doRedPacketStatus(RuleSet ruleSet, String srcStatus) throws CustomException {
		
		if (Status.ALR_DISABLE.toString().equals(ruleSet.getStatus())) {
			// 禁用
			redPacketService.modityStatusByRuleId(ruleSet.getId(), ruleSet.getSysId(), Status.ALR_DISABLE.toString());
		} else if (Status.ALR_ENABLE.toString().equals(ruleSet.getStatus())) {
			// 激活
			if (Status.NOT_ACTIVATE.toString().equals(srcStatus) && ruleSet.getCreateNum() != null && ruleSet.getCreateNum().intValue() > 0) {
				// 第一次激活
				// List<RedPacket> list = new ArrayList<RedPacket>();
				
				/*for (int i = 0; i < ruleSet.getCreateNum(); i++) {
					
					list.add(red);
				}*/
				
				boolean isExist = redisUtils.exists(CREATE_RED);
				if (isExist) {
					throw new CustomException(ErrorCode.DB_EXCEPTION.getCode(), "有进程正在努力创建红包中，请稍等重试");
				}
				RedPacket red = new RedPacket();
				red.setCreateRuleId(ruleSet.getId());
				red.setUseRuleId(ruleSet.getId());
				red.setCreateId(ruleSet.getCreateId());
				red.setCreateTime(DateUtils.getCurrentDateTime());
				red.setUpdateId(ruleSet.getCreateId());
				red.setUpdateTime(DateUtils.getCurrentDateTime());
				red.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
				red.setStartTime(ruleSet.getStartTime());
				red.setEndTime(ruleSet.getEndTime());
				red.setSysId(ruleSet.getSysId());
				red.setRemark(red.getRemark());
				red.setStatus(RedPackStatus.INACTIVE);
				if (ShowType.CASH.toString().equals(ruleSet.getShowType())) {
					red.setAmountOrDiscount(ruleSet.getAmount());
					red.setRedPacketType(RedPackType.DISCOUNT_AMOUNT);
				} else {
					red.setAmountOrDiscount(ruleSet.getDiscount());
					red.setRedPacketType(RedPackType.DISCOUNT);
				}
				red.setRedPacketKey(CommonUtils.getUUID());
				
				String[] list = new String[ruleSet.getCreateNum()];
				if (list.length > 0) {
					ThreadPoolUtils.getThreadPool().execute(new Runnable() {
						public void run() {
							try {
								redisUtils.set(CREATE_RED, "true", 60);
								if (ruleSet.getCreateNum() < INSERT_RED) {
									redPacketService.insertBatch(list, red);
								} else {
									// 分批插入
									int num = 0;
									int remainder = list.length % INSERT_RED;
									if (remainder == 0) {
										num = list.length / INSERT_RED;
									} else {
										num = (list.length / INSERT_RED) + 1;
									}
									for (int i = 0; i < num; i++) {
										if (i == num - 1 && remainder != 0) {
											redPacketService.insertBatch(new String[remainder], red);
										} else {
											redPacketService.insertBatch(new String[INSERT_RED], red);
										}
									}
								}
							} catch (Exception e) {
								log.error("创建红包失败：" + e);
							} finally {
								boolean isExist = redisUtils.exists(CREATE_RED);
								if (isExist) {
									redisUtils.del(CREATE_RED);
								}
								log.info("根据会员等级派发--结束");
							}
						}
					});
					
				}
				
			} // else {
				// redPacketService.modityStatusByRuleId(ruleSet.getId(), ruleSet.getSysId(),
				// Status.ALR_ENABLE.toString());
				// }
		}
	}
	
	/**
	 * @param skus
	 * @param sysId
	 * @param level
	 * @return
	 */
	public List<SpecialPriceVo> findSpecialPriceBySkus(List<String> skus, Long sysId, String level, String device) {
		List<SpecialPriceVo> svoList = new ArrayList<>();
		if (skus != null && skus.size() > 0) {
			svoList = ruleSetMapper.findSpecialPriceBySkus(sysId, skus, device);
			/*
			 * for (SpecialPriceVo svo : svoList) { if (!StringUtil.isBlank(svo.getMemberLevel())) { String[] memberLevels = svo.getMemberLevel().split(","); if (memberLevels != null &&
			 * memberLevels.length > 0) { for (String memberLevel : memberLevels) { if (memberLevel.equals(level)) { returnList.add(svo); } } } } }
			 */
		}
		return svoList;
		
	}
	
	@Override
	public List<RuleSet> findRuleSetListByIds(List<Long> ruleIds, RuleSet rs) {
		return ruleSetMapper.findRuleSetListByIds(ruleIds, rs);
	}
	
	public List<RuleSet> findRule(RuleSet rs, String orderBy, String sort) {
		return ruleSetMapper.findRuleList(rs, orderBy, sort);
	}
	
	/**
	 * 派发用户行为
	 * 
	 * @param sysId
	 * @param sysUserId
	 * @param memberId
	 * @param device
	 * @param activityType
	 * @throws CustomException
	 * @throws ParseException
	 */
	@Transactional(rollbackFor = Exception.class)
	public void sendByUserBehavior(Long sysId, Long sysUserId, Long memberId, String device, String activityType) throws CustomException, ParseException {
		RuleSet param = new RuleSet();
		param.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
		param.setRuleType(RuleType.USER_BEHAVIOR.toString());
		param.setStatus(Status.ALR_ENABLE.toString());
		String currTime = DateUtils.getCurrentDateTime();
		param.setStartTime(currTime);
		param.setEndTime(currTime);
		param.setSysId(sysId);
		param.setDevice(device);
		param.setActivityType(activityType);
		List<RuleSet> list = this.findRule(param, "enableTime", "DESC");
		
		if (list == null || list.size() < 1) {
			log.info("查无相应的用户行为规则，无法派送");
			return;
		}
		MemberLevel memberLevel = null;
		if (ShowType.LOGIN.toString().equals(activityType)) {
			memberLevel = memberLevelService.findByMemberIdAndSysId(memberId, sysId);
			if (memberLevel == null) {
				throw new CustomException(ErrorCode.RULE_OUT_MEMBER_LEVEL.getCode(), "会员等级不符合要求");
			}
		}
		
		for (RuleSet rs : list) {
			if (ShowType.LOGIN.toString().equals(activityType)) {
				boolean isLevelSuccess = this.checkLimitMemberLevel(memberLevel, rs);
				if (!isLevelSuccess) {
					// log.info("会员行为：规则限制等级-" + rs.getLimitMemberLevel() + "，memberId为" + memberId + "等级为" + memberLevel.getId());
					log.info("会员行为：规则限制等级-{}，memberId为{}等级为{}", rs.getLimitMemberLevel(), memberId, memberLevel.getId());
					continue;
				}
				LoginRuleNum findNum = new LoginRuleNum();
				findNum.setRuleId(rs.getId());
				findNum.setMemberId(memberId);
				findNum.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
				findNum.setSysId(sysId);
				List<LoginRuleNum> loginList = loginRuleNumService.findListBySelect(findNum);
				if (loginList == null || loginList.size() < 1) {
					try {
						loginRuleNumService.insert(findNum);
					} catch (Exception e) {
						log.info("插入登录记录出错" + e.getMessage());
						continue;
					}
					
				} else {
					// log.info("会员行为：首次登录-" + "，memberId为" + memberId + "对应的规则Id" + rs.getId() + "登录了" + loginList.size() + "次");
					log.info("会员行为：首次登录，memberId为{}对应的规则Id{}登录了{}次", memberId, rs.getId(), loginList.size());
					continue;
				}
			}
			
			// 送积分
			if (ShowType.GIVE_INTEGRAL.toString().equals(rs.getShowType())) {
				// log.info("用户行为--送积分memberId=" + memberId + "数量=" + rs.getGiveNum());
				log.info("用户行为--送积分memberId={}数量={}", memberId, rs.getGiveNum());
				if (ShowType.REG.toString().equals(activityType)) {
					integralRecordService.addIntegralRecord(memberId, sysId, null, null, rs.getGiveNum().intValue(), IntegralType.REGISTER, "注册", "", "", IntegralRecord.IS_BUY_NO);
				} else {
					integralRecordService.addIntegralRecord(memberId, sysId, null, null, rs.getGiveNum().intValue(), IntegralType.LOGIN_GIVE, "登录", "", "",
							IntegralRecord.IS_BUY_NO);
				}
			}
			// 送抽奖次数
			if (ShowType.GIVE_DRAW_NUM.toString().equals(rs.getShowType())) {
				// log.info("用户行为--抽奖次数memberId=" + memberId + "数量=" + rs.getGiveNum());
				log.info("用户行为--抽奖次数memberId={}数量={}", memberId, rs.getGiveNum());
				if (!StringUtil.isBlank(rs.getGiveCode()) && rs.getGiveNum() != null && rs.getGiveNum().intValue() > 0) {
					String[] no = rs.getGiveCode().split(",");
					for (int i = 0; i < no.length; i++) {
						drawNumService.modityDrawNum(memberId, Long.valueOf(no[i]), sysId, rs.getGiveNum().intValue(), null);
					}
				}
			}
			// 送充值
			if (ShowType.GIVE_TOPUP_BALANCE.toString().equals(rs.getShowType())) {
				// log.info("用户行为--送充值memberId=" + memberId + "数量=" + rs.getGiveNum());
				log.info("用户行为--送充值memberId={}数量={}", memberId, rs.getGiveNum());
				if (ShowType.REG.toString().equals(activityType)) {
					balanceRecordService.updateBalance(memberId, sysId, null, null, rs.getGiveNum(), BalanceType.REG_GIVE, "注册", "", "", BalanceRecord.IS_BUY_NO);
				} else {
					balanceRecordService.updateBalance(memberId, sysId, null, null, rs.getGiveNum(), BalanceType.LOGIN_GIVE, "登录", "", "", BalanceRecord.IS_BUY_NO);
				}
			}
			// 送红包
			if (ShowType.GIVE_RED_PACKET.toString().equals(rs.getShowType())) {
				// log.info("用户行为--送红包memberId=" + memberId + "数量=" + rs.getGiveNum());
				log.info("用户行为--送红包memberId={}数量={}", memberId, rs.getGiveNum());
				if (!StringUtil.isBlank(rs.getGiveCode()) && rs.getGiveNum() != null && rs.getGiveNum().intValue() > 0) {
					String[] no = rs.getGiveCode().split(",");
					List<Long> ruleIds = new ArrayList<>();
					for (int i = 0; i < no.length; i++) {
						ruleIds.add(Long.valueOf(no[i]));
					}
					redPacketService.sendRedPacket(ruleIds, sysId, rs.getGiveNum().intValue(), memberId, SysUser.SYS_USER, rs.getId(),
							RuleType.USER_BEHAVIOR.toString() + "_" + PrizeType.GIVE_RED_PACKET.toString(), null);
				}
			}
			// 送商品
			if (ShowType.GIVE_PRO.toString().equals(rs.getShowType())) {
				// log.info("用户行为--送商品memberId=" + memberId + "数量=" + rs.getGiveNum());
				log.info("用户行为--送商品memberId={}数量=", memberId, rs.getGiveNum());
				if (!StringUtil.isBlank(rs.getGiveCode()) && rs.getGiveNum() != null && rs.getGiveNum().intValue() > 0) {
					String[] no = rs.getGiveCode().split(",");
					List<String> skus = new ArrayList<>();
					for (int i = 0; i < no.length; i++) {
						skus.add(no[i]);
					}
					shoppingCartService.addPremium(skus, sysId, memberId, rs.getGiveNum(), rs.getId(), rs.getShowName());
				}
			}
		}
	}
	
	/**
	 * 根据序列号查询
	 * 
	 * @param serialNumber
	 */
	public RuleSet selectBySerialNumber(String serialNumber) {
		return ruleSetMapper.selectBySerialNumber(serialNumber);
	}
	
	/**
	 * 根据Idlist和规则类型查询规则
	 */
	@Override
	public PageResult<List<RuleResponseVo>> findRuleListByIds(String ids, String ruleType, Integer pageNumber, Integer pageSize, Long sysId, String status) {
		String[] idArray = null;
		if (!StringUtil.isEmpty(ids)) {
			ids = ids.replace(" ", "");
			idArray = ids.split(",");
		}
		List<Long> ruleIds = new ArrayList<>();
		if (idArray != null) {
			for (int i = 0; i < idArray.length; i++) {
				if (!StringUtil.isEmpty(idArray[i])) {
					try {
						ruleIds.add(Long.valueOf(idArray[i]));
					} catch (Exception e) {
						log.info("编码传中文跳过");
					}
					
				}
			}
		}
		
		RuleSet rs = new RuleSet();
		rs.setSysId(sysId);
		rs.setRuleType(ruleType);
		rs.setStatus(status);
		if (!StringUtil.isBlank(status)) {
			rs.setValidPeriodType((short) 3);// 3 要特殊处理
		}
		PageHelper.startPage(pageNumber, pageSize);
		List<RuleSet> redRuleList = ruleSetMapper.findRuleSetListByIds(ruleIds, rs);
		PageInfo<RuleSet> page = new PageInfo<>(redRuleList);
		PageResult<List<RuleResponseVo>> pageObjectVo = new PageResult<>();
		List<RuleResponseVo> volist = new ArrayList<>();
		for (RuleSet temp : redRuleList) {
			RuleResponseVo vo = new RuleResponseVo();
			vo.setShowName(temp.getShowName());
			vo.setId(temp.getId());
			vo.setStatus(temp.getStatus());
			vo.setRuleType(temp.getRuleType());
			volist.add(vo);
		}
		pageObjectVo.setData(volist);
		pageObjectVo.setTotal_record(Integer.valueOf(page.getTotal() + ""));
		pageObjectVo.setErrorCode(ErrorCode.SUCCESS);
		return pageObjectVo;
		
	}
	
	/** 
	 *
	 * @Title: findRuleSetListByIds 
	 * @author: wuyicheng
	 * @date: 2017年7月18日下午2:45:29 
	 * @param ruleIds
	 * @return
	 * @throws 
	 */
	@Override
	public List<RuleSet> findRuleSetListByIds(List<Long> ruleIds) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/**
	 * 修改红包已使用的数量
	 * @Title: modityUseNumByRuleSet 
	 * @Description: TODO
	 * @author xjd
	 * @param @param ruleSetId
	 * @param @param useNum
	 * @throws
	 */
	@Override
	public void modityUseNumByRuleSet(Long ruleSetId, int useNum) {
		ruleSetMapper.modityUseNumByRuleSet(ruleSetId, useNum);
		
	}
	
}
